import getopt
import sys
import json

from flask import Flask, request, Response
from consulkv import Config
from logging.config import dictConfig
from mongodb import Mongodb
from message import SendMessage
from Tredis import Count
import requests

# 连接consul配置中心
consul = Config()
# 获取服务配置
config = consul.get(key='consul-watch')
dictConfig(json.loads(config['logger_dict']))
consul_host = config['CONSUL_TEST_HOST'] if params[3] == 'test' else config['CONSUL_PRO_HOST']
robot_url = config['ROBOT_URL_TEST'] if params[3] == 'test' else config['ROBOT_URL_PRO']
# 注册app
app = Flask(__name__)


@app.route('/watch', methods=['POST'])
def watch():
    dicli = []
    data = request.json
    col_name = data[0]['Key'].split("/")[0]
    for d in data:
        if d['Value']:
            dic = {'KEY': d['Key'], "VALUE": d["Value"]}
            dic_li.append(dic)
    Mongodb(col_name, dic_li, config['MONGO_HOST'], config['MONGO_DATABASE'], robot_url, consul_host)
    app.logger.info(data)
    return Response("Post")


@app.route('/service', methods=['POST'])
def service():
    data = request.json
    app.logger.info(data)
    if data:
        for service in data:
            if service['Output']:
                count = Count(service['ServiceID'], host=config['REDIS_HOST'], port=int(config['REDIS_PORT']))
                healthy_check_url = service['Output'].split(' ')[1].rstrip(':')
                if count >= 5:
                    status = healthCheck(healthy_check_url)
                    info = {'Type': '微服务{}检查超时{}次'.format(service['ServiceID'], count),
                            'Name': service['ServiceID'],
                            'Output': service['Output'],
                            'Status': status}
                    if not status:
                        SendMessage(info, robot_url, consul_host)
                if count >= 10:
                    delete_url = config['CONSUL_DELETE_HOST'] + "v1/agent/service/deregister/" + service[
                        'ServiceID']
                    status = healthCheck(healthy_check_url)
                    if status is not True:
                        requests.put(delete_url)
                        info = {'Type': '微服务{}检查超时{}次'.format(service['ServiceID'], count),
                                'Name': service['ServiceID'],
                                'Output': "微服务已从consul删除",
                                'Status': status}
                        SendMessage(info, robot_url, consul_host)
            else:
                info = {'Type': '微服务{}启动'.format(service['ServiceID']), 'Name': service['ServiceID'],
                        'Output': service['Output'], 'Status': 'Started'}
                SendMessage(info, robot_url, consul_host)
    return Response("post")


def healthCheck(url):
    try:
        response = requests.get(url=url, timeout=3).json()
        status = response['status']
        return status
    except:
        return False


if __name__ == '__main__':
    app.run(port=9000, host='0.0.0.0')
